console.log('content.js')

var apiUrl;

function initUrl() {
    apiUrl = localStorage.getItem("apiUrl") || 'http://localhost:5000';
}

initUrl();

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if(request.apiUrl){
            apiUrl = request.apiUrl;
            localStorage.setItem("apiUrl",apiUrl)
        }
        sendResponse({ farewell: "ok" });
    });


const html = `
    <select></select>
    <button>下载</button>
`
function createYdownloadElem(id) {

    let newParagraph = document.createElement("div");
    newParagraph.id = id;
    newParagraph.innerHTML = html;
    let referenceNode = document.querySelector("#top-row");
    let parentNode = referenceNode.parentNode;
    parentNode.insertBefore(newParagraph, referenceNode);

    document.querySelector('#ydownload button').addEventListener('click', function () {
        const sd = document.querySelector('#ydownload select').value;

        if (sd) {

            var json = JSON.parse(sd);

            const data = {
                url: href,
                formatId: json.id,
                uid: json.uid,
                ext: json.ext,
                resolution: json.resolution
            };

            fetch(`${apiUrl}/download`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Success:', data);
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }


    })

}


function updateInfo() {
    if (href != window.location.href) {
        href = window.location.href
        var id = 'ydownload';
        if (!document.getElementById(id)) {
            createYdownloadElem(id)
        }
        document.querySelector(`#${id} select`).innerHTML = '';
        fetch(`${apiUrl}/download?url=${encodeURIComponent(href)}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json();
            })
            .then(data => {
                if (data.code == 0) {
                    var html = '';
                    for (var i = 0; i < data.data.length; i++) {
                        var d = data.data[i];
                        const sd = JSON.stringify(d);
                        if (d.ch) {
                            html += `<option value='${sd}'>[视频+音频${d.resolution}.${d.ext}]</option>`;
                        } else if (d.resolution == 'audio') {
                            html += `<option value='${sd}'>[音频.${d.ext}]</option>`;
                        } else {
                            html += `<option value='${sd}'>[视频${d.resolution}.${d.ext}]</option>`;
                        }

                    }
                    document.querySelector(`#${id} select`).innerHTML = html;

                }

            })
            .catch(error => {
                console.error('Error:', error);

            });
    }
}


var timeoutIndex;
var href;
function loadElem() {
    if (document.getElementById('primary')) {
        //添加监听
        const targetNode = document.getElementById('primary');
        const config = { attributes: true, childList: true, subtree: true };
        const callback = function (mutationsList, observer) {
            if (timeoutIndex) {
                clearTimeout(timeoutIndex)
                timeoutIndex = null;
            }
            setTimeout(() => {
                updateInfo()
            }, 500)
        };
        const observer = new MutationObserver(callback);
        observer.observe(targetNode, config);

    } else {
        setTimeout(() => {
            loadElem();
        }, 500)
    }
}

loadElem();



